<template>
  <div>
    <!--面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="9">
          <!-- 搜索输入框 -->
          <div>
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              :clearable="true"
              @clear="getuserlist()"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getuserlist()"
              ></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <!-- 添加用户按钮 -->
          <div>
            <el-button type="primary" @click="dialogVisible = true"
              >添加用户</el-button
            >
          </div>
        </el-col>
      </el-row>
      <!-- 用户表单数据 -->
      <el-table
        style="width: 100%"
        :border="true"
        :stripe="true"
        :data="userlist"
      >
        <el-table-column label="#" width="50" type="index"> </el-table-column>
        <el-table-column label="姓名" width="180" prop="username">
        </el-table-column>
        <el-table-column label="邮箱" width="180" prop="email">
        </el-table-column>
        <el-table-column label="电话" width="180" prop="mobile">
        </el-table-column>
        <el-table-column label="角色" width="180" prop="role_name">
        </el-table-column>
        <el-table-column label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userstatechange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="getmodifyuser(scope.row.id)"
            ></el-button>

            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteuser(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-star-off"
                @click="roleinfo(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 增加用户弹出框 -->
    <el-dialog
      title="增加用户"
      :visible.sync="dialogVisible"
      width="30%"
      @close="addDialogClosed()"
    >
      <el-form
        :model="newuser"
        :rules="newuserrules"
        label-width="70px"
        ref="newuserRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
            v-model="newuser.username"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            v-model="newuser.password"
            show-password
          >
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            prefix-icon="el-icon-user"
            placeholder="请输入邮箱"
            v-model="newuser.email"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input
            prefix-icon="el-icon-mobile-phone"
            placeholder="请输入手机号"
            v-model="newuser.mobile"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduserinfo()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息弹出框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="dialogVisiblemodify"
      width="30%"
    >
      <el-form
        :model="modifyuser"
        :rules="newuserrules"
        label-width="70px"
        ref="modifyuseRef"
      >
        <el-form-item label="用户名">
          <el-input
            prefix-icon="el-icon-user"
            v-model="modifyuser.username"
            disabled
          >
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input prefix-icon="el-icon-user" v-model="modifyuser.email">
          </el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input prefix-icon="el-icon-user" v-model="modifyuser.mobile">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisiblemodify = false">取 消</el-button>
        <el-button type="primary" @click="modifyuserinfo()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户角色弹出框 -->
    <el-dialog
      title="修改用户角色"
      :visible.sync="dialogVisibleRole"
      width="30%"
    >
      <el-form :model="userRole" label-width="100px" ref="modifyUseRoleRef">
        <el-form-item label="当前用户 ">
          {{ userRole.username }}
        </el-form-item>
        <el-form-item label="当前角色 ">
          {{ userRole.role_name }}
        </el-form-item>
      </el-form>
      <div>
        <p>
          分配新角色
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="dialogVisibleRole = false">取 消</el-button>
        <el-button type="primary" @click="modifyUserRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //获取用户参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      // 用户列表
      userlist: [],
      total: 10,
      // 角色列表
      roles: [],
      selectedRoleId: "",
      // 分配角色用户
      userRole: {},
      // 弹出框显示控制
      dialogVisible: false,
      dialogVisiblemodify: false,
      dialogVisibleRole: false,
      // 增加用户参数
      newuser: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 通过id获取的用户对象
      modifyuser: {},
      // 验证规则
      newuserrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3-5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6-15 个字符", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // { validator: checkPhone, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //获取用户数据
    async getuserlist() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      console.log(res.data);
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    //分页,每页显示量改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getuserlist();
    },
    //换页
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getuserlist();
    },
    //改变用户状态
    async userstatechange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("修改用户状态失败");
      }
      this.$message.success("修改用户状态成功");
    },
    //重置增加用户弹出框的表单数据
    addDialogClosed() {
      this.$refs.newuserRef.resetFields();
    },
    //发送增加用户请求
    adduserinfo() {
      this.$refs.newuserRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.newuser);
        console.log(res);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success("增加用户成功");
        this.dialogVisible = false;
        this.getuserlist();
      });
    },
    //通过id获取用户数据
    async getmodifyuser(id) {
      const { data: res } = await this.$http.get("users/" + id);
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      // this.$message.success("获取成功");
      this.modifyuser = res.data;
      this.dialogVisiblemodify = true;
    },
    //发送修改用户信息请求
    modifyuserinfo() {
      this.$refs.modifyuseRef.validate(async (valid) => {
        const { data: res } = await this.$http.put(
          "users/" + this.modifyuser.id,
          { email: this.modifyuser.email, mobile: this.modifyuser.mobile }
        );
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("更新失败");
        this.$message.success("更新成功");
        this.dialogVisiblemodify = false;
        this.getuserlist();
      });
    },
    //删除用户,出现弹出框询问是否删除
    deleteuser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + id);
          if (res.meta.status == 400) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getuserlist();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //打开修改用户角色弹框
    roleinfo(user) {
      this.userRole = user;
      this.getroles();
      this.dialogVisibleRole = true;
    },
    // 获取角色列表
    async getroles() {
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("获取角色列表失败");
      this.roles = res.data;
      // this.$message.success("获取角色列表成功");
    },
    // 发送修改用户角色请求
    async modifyUserRole() {
      const { data: res } = await this.$http.put(
        `users/${this.userRole.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      );
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("修改失败");
      this.getuserlist();
      this.dialogVisibleRole = false;
    },
  },
  created() {
    this.getuserlist();
  },
};
</script>
<style lang='less' scoped>
</style>